package org.biubiu0002.baiblog.im.utils;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.http.*;

import java.nio.charset.StandardCharsets;

/**
 * @Author: biubiu0002
 * @Date: 2022/9/2 10:08
 **/
public class HttpHelper {

    public static void sendOK(Channel channel,Object data){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",0);
        jsonObject.put("msg","success");
        if(data!=null){
            jsonObject.put("data",data);
        }
        String jsonString = jsonObject.toJSONString();
        doSendOk(channel,jsonString);
    }

    public static void sendBizException(Channel channel,String code,String msg){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code",code);
        jsonObject.put("msg",msg);
        String jsonString = jsonObject.toJSONString();
        sendException(channel,HttpResponseStatus.OK,jsonString);
    }

    public static void sendException(Channel channel,HttpResponseStatus status,String json){
        doSend(channel,status,json);
    }

    public static boolean checkRequest(Channel channel, FullHttpRequest fullHttpRequest){
        DecoderResult decoderResult = fullHttpRequest.decoderResult();
        if(!decoderResult.isSuccess()){
            String cause = decoderResult.toString();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code","A0003");
            jsonObject.put("msg","输入格式有误，请检查输入格式: "+cause);
            sendException(channel,HttpResponseStatus.BAD_REQUEST, jsonObject.toJSONString());
            return false;
        }
        return true;
    }

    public static void doSend(Channel channel, HttpResponseStatus status,String json){
        ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.directBuffer().writeBytes(json.getBytes(StandardCharsets.UTF_8));
        DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,byteBuf);
        response.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json; charset=UTF-8");
        HttpUtil.setContentLength(response,response.content().readableBytes());
        HttpUtil.setKeepAlive(response,true);
        channel.writeAndFlush(response);
    }

    public static void doSendOk(Channel channel,String json){
        doSend(channel,HttpResponseStatus.OK,json);
    }


}
